﻿using System;
using System.Collections.Generic;
using System.Linq;
using Leo.Blog.DAL.SysModule;
using Leo.Blog.Model;
using Leo.Blog.ViewModel;
using Leo.Blog.ViewModel.SysModule;

namespace Leo.Blog.BLL.SysModule
{
    public class Sys_Modules_B
    {

        /// <summary>
        /// 获取所有的模组信息，分页使用
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="parentId">根节点都为0，如果查询全部，则parentId=-1</param>
        /// <returns></returns>
        public static List<SysModuleVM> GetSysModules(int pageIndex, int pageSize, out int totalCount, int parentId = -1)
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            List<Sys_Modules> listSysModules;
            if (parentId == -1)
            {
                listSysModules = _sysModulesD.LoadPageEntities(pageIndex, pageSize, out totalCount,
                    null, true, m => m.ModuleId).ToList();
            }
            else
            {
                //m => m.ParentModuleId == parentId
                //
                // 如果是 1-2-3-41 需要查询包含1的，可以左右加上分隔符'-1-2-3-41-',用'-1-'查询
                listSysModules = _sysModulesD.LoadPageEntities(pageIndex, pageSize, out totalCount,
                    m => ("-" + m.ModulePath + "-").Contains("-" + parentId + "-"), true, m => m.ModuleId).ToList();
            }

            var listSysModuleVM = (from lsm in listSysModules
                select new SysModuleVM
                {
                    ModuleId = lsm.ModuleId,
                    ModuleName = lsm.ModuleName,
                    ModuleDesc = lsm.ModuleDesc,
                    WebUrl = lsm.WebUrl,
                    UrlPara=lsm.UrlPara,
                    ParentModuleId = lsm.ParentModuleId,
                    ParentName = lsm.ParentName,
                    ModulePath=lsm.ModulePath,
                    SortNo = lsm.SortNo,
                    IsAutoExpend = lsm.IsAutoExpend,
                    IconName = lsm.IconName,
                    IsEnable = lsm.IsEnable,
                    CreateBy = lsm.CreateBy,
                    CreateDT = lsm.CreateDT
                }).ToList();
            return listSysModuleVM;
        }
        /// <summary>
        /// 获取所有的模组信息
        /// </summary>
        /// <returns></returns>
        public static List<Sys_Modules> GetSysModulesAll()
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            List<Sys_Modules> modules = _sysModulesD.LoadList().ToList();
            return modules;
        }
        /// <summary>
        /// 获取所有有效的模组信息
        /// </summary>
        /// <returns></returns>
        public static List<Sys_Modules> GetSysModulesAllIsEnable()
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            List<Sys_Modules> modules = _sysModulesD.LoadList(m=>m.IsEnable==1).ToList();
            return modules;
        }
        /// <summary>
        /// 选择孩子List
        /// </summary>
        /// <param name="listModules"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private static List<Sys_Modules> GetChildrenByParentId(List<Sys_Modules> listModules, int parentId=0)
        {
            List<Sys_Modules> listChilren = listModules.Where(m=>m.ParentModuleId==parentId).OrderBy(m=>m.SortNo).ToList();
            return listChilren;
        }
        /// <summary>
        /// 针对用户具有的模组查找子集
        /// </summary>
        /// <param name="listModules"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static List<UserModule> GetUserModulesByParentId(List<UserModule> listModules, int parentId = 0)
        {
            List<UserModule> listChilren = listModules.Where(m => m.ParentModuleId == parentId).OrderBy(m => m.SortNo).ToList();
            return listChilren;
        }
        /// <summary>
        /// 递归生成模组树
        /// </summary>
        /// <param name="rootNode">树的根节点</param>
        /// <param name="listModules">生成数的所有节点</param>
        /// <param name="parentId">父节点id,默认根节点ID为0</param>
        public static void GetTree(TreeNode rootNode, List<Sys_Modules> listModules, int parentId)
        {
            var listParent = GetChildrenByParentId(listModules, parentId);
            foreach (var item in listParent)
            {
                var listChild = GetChildrenByParentId(listModules, item.ModuleId);
                TreeNode tn = new TreeNode();
                tn.Id = item.ModuleId;
                tn.Text = item.ModuleName;
                //tn.IconName = item.IconName;
                tn.State = item.IsAutoExpend.Value == 1 ? "open" : "closed";
                tn.IsChecked = false;
                tn.Attributes = new { ParentID = item.ParentModuleId };//默认设置
                if (listChild != null)
                {
                    GetTree(tn, listModules, item.ModuleId);
                }
                rootNode.Children.Add(tn);
            }
        }
        //根据所有模块信息生成树
        public static void GetTreeByAllList(TreeNode rootNode, int parentId) {
            List<Sys_Modules> moduleList = GetSysModulesAll();
            GetTree(rootNode, moduleList,parentId);
        }
        //根据所有有效的模块生成树
        public static void GetTreeByAllIsEnable(TreeNode rootNode, int parentId)
        {
            List<Sys_Modules> moduleList = GetSysModulesAllIsEnable();
            GetTree(rootNode, moduleList, parentId);
        }

        public static SysModuleVM FindSingle(int moduleId)
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            Sys_Modules modules = _sysModulesD.FindSingle(m=>m.ModuleId==moduleId);
            if (modules != null)
            {
                SysModuleVM vm = new SysModuleVM
                {
                    ModuleId = modules.ModuleId,
                    ModuleName = modules.ModuleName,
                    ModuleDesc = modules.ModuleDesc,
                    WebUrl = modules.WebUrl,
                    UrlPara = modules.UrlPara,
                    ParentModuleId = modules.ParentModuleId,
                    ParentName = modules.ParentName,
                    SortNo = modules.SortNo,
                    ModulePath=modules.ModulePath,
                    IsAutoExpend = modules.IsAutoExpend,
                    IconName = modules.IconName,
                    IsEnable = modules.IsEnable,
                    CreateBy = modules.CreateBy,
                    CreateDT = modules.CreateDT
                };
                return vm;
            }
            return null;
        }

        public static SysModuleVM AddorUpdate(SysModuleVM model)
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            Sys_Modules module = _sysModulesD.FindSingle(m => m.ModuleId == model.ModuleId);
            if (module == null)
            {
                #region 增加
                Sys_Modules sysMmodule = new Sys_Modules
                {
                    ModuleName = model.ModuleName,
                    ModuleDesc = model.ModuleDesc,
                    WebUrl = model.WebUrl,
                    ParentModuleId = model.ParentModuleId,
                    ParentName = model.ParentName,
                    ModulePath=model.ModulePath,
                    SortNo = model.SortNo,
                    IsAutoExpend = model.IsAutoExpend,
                    IconName = model.IconName,
                    IsEnable = model.IsEnable,
                    CreateBy = model.CreateBy,
                    CreateDT = DateTime.Now,
                    LastEditBy = model.CreateBy,
                    LastEditDT = DateTime.Now
                };
               Sys_Modules obj= _sysModulesD.AddEntity(sysMmodule);
               if (obj != null) {
                   return model;
               }
               return null;
                #endregion
            }
            else
            {
                string srcModulePath = module.ModulePath;
                #region 修改
                module.ModuleName = model.ModuleName;
                module.ModuleDesc = model.ModuleDesc;
                module.WebUrl = model.WebUrl;
                module.ParentModuleId = model.ParentModuleId;
                module.ParentName = model.ParentName;
                module.ModulePath = model.ModulePath;
                module.SortNo = model.SortNo;
                module.IsAutoExpend = model.IsAutoExpend;
                module.IconName = model.IconName;
                module.IsEnable = model.IsEnable;
                module.LastEditBy = model.CreateBy;
                module.LastEditDT = DateTime.Now;

                if (_sysModulesD.UpdateEntity(module)) {
                    if (!srcModulePath.Equals(model.ModulePath))
                    {
                        string moduleId = "-" + module.ModuleId + "-";
                        //修改后路径相同，不更新子项路径，路径不相同，需要更新路径
                        string sql = @"update Sys_Modules set ModulePath=(select ModulePath+'-'+cast(ModuleId as varchar) FROM Sys_Modules WHERE ModuleId='" + module.ModuleId
                            + "')  where ModuleId in(select ModuleId from Sys_Modules where ('-'+ModulePath+'-') like '%-" + module.ModuleId + "-%')";
                        int res = _sysModulesD.ExecuteCommand(sql);
                    }
                    return model;
                }
                return null;
                #endregion
            }
        }

        public static bool UpdateIsEnable(int moduleId,int userId)
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            Sys_Modules module = _sysModulesD.FindSingle(m => m.ModuleId == moduleId);
            if(module!=null){
                module.IsEnable = module.IsEnable == 1 ? 0 : 1;
                module.LastEditBy = userId;
                module.LastEditDT = DateTime.Now;
                return _sysModulesD.UpdateEntity(module);
            }
            return false;
        }

        public static bool Delete(int moduleId)
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            Sys_Modules module = _sysModulesD.FindSingle(m => m.ModuleId == moduleId);
            if (module != null)
            {
                return _sysModulesD.DeleteEntity(module);
            }
            return false;
        }

        public static bool DeleteList(string ids) {
            List<Sys_Modules> moduleList = new List<Sys_Modules>();
            foreach (string id in ids.Split(','))
            {
                if (string.IsNullOrEmpty(id)) { continue; }
                moduleList.Add(new Sys_Modules {ModuleId=int.Parse(id) });
            }
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            return _sysModulesD.DeleteList(moduleList);
        }


    }
}
